package com.mediacloud.app.newsmodule.view.share

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.provider.Settings
import android.view.View
import android.widget.RelativeLayout
import androidx.fragment.app.FragmentActivity
import com.mediacloud.app.assembly.util.BitmapUtil
import com.mediacloud.app.assembly.util.FileUtil
import com.mediacloud.app.assembly.util.Utility
import com.mediacloud.app.assembly.util.toastCenter
import com.mediacloud.app.model.interfaces.IPermissionsAgree
import com.mediacloud.app.model.interfaces.PermissionUtil
import com.mediacloud.app.model.utils.ViewUtils
import com.mediacloud.app.newsmodule.R
import com.mediacloud.app.newsmodule.utils.NavigationBarTools
import com.mediacloud.app.newsmodule.utils.share.ShareMemberBeen
import com.mediacloud.app.share.SocialShareControl
import com.mediacloud.app.share.view.SharePopGridWindow
import org.jetbrains.anko.doAsync
import org.jetbrains.anko.uiThread
import java.io.File


abstract class AbsPosterSharePop(context: Context) : SharePopGridWindow(context), IPosterSharePop {
    var posterContainer: RelativeLayout = contentView.findViewById(R.id.posterContainer)
    var posterMode = false
    var shareBeen: ShareMemberBeen? = null


    init {
        posterContainer.visibility = View.GONE
        posterContainer.setOnClickListener { }
    }

    override fun isPosterShareMode(): Boolean {
        return posterMode
    }

    override fun setPosterShareMode(posterMode: Boolean) {
        this.posterMode = posterMode
    }

    override fun dismiss() {
        posterContainer.visibility = View.GONE
        posterMode = false
        super.dismiss()
    }

    override fun getResLayoutId(): Int {
        return R.layout.share_pop_win_root
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
//        if (!DeviceUtils.isCus(context)) {
//            findViewById<View>(R.id.tv_tip_195)?.visibility = View.VISIBLE
//        }
        if (NavigationBarTools.checkDeviceHasNavigationBar(context)) {//打开分享弹窗隐藏导航栏，多款手机不好适配
            window!!.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
            window!!.decorView.setOnSystemUiVisibilityChangeListener {
                var uiOptions =
                    //隐藏导航栏
                    View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                uiOptions = uiOptions or 0x00001000
                window!!.decorView.systemUiVisibility = uiOptions
            }
        }


    }


    override fun getFitSystemWindow(): Boolean {
        return true
    }

    var mActivity: Activity? = null
    override fun show(activity: Activity) {
        super.show()
        mActivity = activity
    }


    override fun shareImage(share_media: Int) {
        PermissionUtil.invokeStoragePermission(
            contentView.context as FragmentActivity,
            object : IPermissionsAgree {
                override fun onAgree() {
                    realShare(share_media)
                }

                override fun onRefuse() {
                }

                override fun hasPermissions() {
                    realShare(share_media)
                }
            })
    }

    private fun realShare(share_media: Int) {
        posterView().let {
            doAsync {
                val bitmap = BitmapUtil.convertViewToBitmap(it)
                if (FileUtil.getPhotoApp() == null) {
                    FileUtil.initPackage(context)
                }
                val path = FileUtil.saveShareBitmap(bitmap)
                if (share_media == 15) {
                    val intent = Intent(context, WbShareActivity::class.java)
                    intent.putExtra("path", path)
                    context.startActivity(intent)
                    return@doAsync
                }
                uiThread {
                    SocialShareControl.share(
                        ViewUtils.searchTintContextHostActivity(context),
                        share_media,
                        path
                    )
                    SocialShareControl.addSocialShareListener(object :
                        SocialShareControl.SocialShareListener {

                        override fun shareComplete(platform: Int, p1: HashMap<String, Any>?) {
                            dismiss()
                            SocialShareControl.removeSocialShareListener(this)
                        }

                        override fun shareCancel(platform: Int) {
                            dismiss()
                            SocialShareControl.removeSocialShareListener(this)
                        }

                        override fun shareError(platform: Int, p1: String?) {
                            dismiss()
                            SocialShareControl.removeSocialShareListener(this)
                        }
                    })
                }
            }

        }
    }


    override fun saveImage() {
        // if(!isFastClick())return
        PermissionUtil.invokeStoragePermission(
            contentView.context as FragmentActivity,
            object : IPermissionsAgree {
                override fun onAgree() {
                    save()
                }

                override fun onRefuse() {
                    dismiss()
                }

                override fun hasPermissions() {
                    save()
                }
            })
    }

    private fun save() {
        doAsync {
            posterView().let {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R && !Environment.isExternalStorageManager()) {
                    val intent = Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION)
                    val uri = Uri.fromParts("package", context.packageName, null)
                    intent.setData(uri)
                    context.startActivity(intent)
                    return@let
                }

                val bitmap = BitmapUtil.convertViewToBitmap(it)
                if (FileUtil.getPhotoApp() == null) {
                    FileUtil.initPackage(context)
                }
                val path = FileUtil.getPhotoApp() + "/" + System.currentTimeMillis() + ".png"
                FileUtil.saveBitmap(path, bitmap)
                uiThread {
                    val file = File(path)
                    Utility.insertIntoMediaStore(
                        contentView.context,
                        false,
                        file,
                        file.lastModified()
                    )
                    toastCenter(contentView.context, "图片保存成功")
                    dismiss()
                    bitmap?.recycle()
                }
            }
        }
    }

    override fun setClickDismiss(boolean: Boolean) {
        clickDismiss = boolean
    }


    abstract fun posterView(): View

    fun shareMediaCard() {
    }

}